package com.yindian.cos.easy.security.form;

import com.yindian.cos.easy.security.entity.User;
import com.yindian.cos.easy.security.UserRepository;
import com.yindian.cos.easy.security.authentication.login.UserDetail;
import com.yindian.cos.easy.security.authentication.login.normal.form.FormLoginUserService;
import com.yindian.cos.easy.security.exception.UserNotFoundException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 表单登录获取用户逻辑实现
 *
 * @author zhangchuanhao
 * @create 2018/11/19
 */
@Log4j2
@Component
public class FormLoginUserServiceImpl implements FormLoginUserService {

    @Autowired
    private EasySecurityProperties easySecurityProperties;

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetail getUserDetail(HttpServletRequest request) {
        String username = easySecurityProperties.getForm().getUsernameParameterName();
        String password = easySecurityProperties.getForm().getPasswordParameterName();
        username = request.getParameter(username);
        password = request.getParameter(password);
        User user = userRepository.getUserByUsername(username);
        if (user == null) {
            throw new UserNotFoundException("用户不存在，username = " + username);
        }
        return new CustomFormUserDetail(user, password);
    }
}
